package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;

	// 引入视图的使用和表几乎一模一样
	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;

	@Override
	public List<JSONObject> getBaseCategoryList() {
		// 一级分类集合
		List<JSONObject> jsonObjects = new ArrayList<>();
		// 一次性查询所有三级分类
		List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
		if(CollectionUtils.isEmpty(baseCategoryViews)){
			return jsonObjects;
		}

		// 根据一级分类id进行分组，key是一级分类的id,value是该组数据作为value
		Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
		category1Map.forEach((category1Id, categoryViews2)->{
			JSONObject jsonObject1 = new JSONObject();
			jsonObjects.add(jsonObject1);
			jsonObject1.put("categoryId",category1Id);
			jsonObject1.put("categoryName",categoryViews2.get(0).getCategory1Name());
			// 二级分类集合
			List<JSONObject> jsonObjects2 = new ArrayList<>();
			jsonObject1.put("categoryChild",jsonObjects2);
			// 根据二级分类的id对数据进行分组,key是二级分类id, value是二级分类下的三级数据
			Map<Long, List<BaseCategoryView>> category2Map = categoryViews2.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
			category2Map.forEach((category2Id, categoryViews3) -> {
				JSONObject jsonObject2 = new JSONObject();
				jsonObjects2.add(jsonObject2);
				jsonObject2.put("categoryId",category2Id);
				jsonObject2.put("categoryName",categoryViews3.get(0).getCategory2Name());
				jsonObject2.put("categoryChild",categoryViews3.stream().map(categoryView3 -> {
					JSONObject jsonObject3 = new JSONObject();
					jsonObject3.put("categoryId", categoryView3.getCategory3Id());
					jsonObject3.put("categoryName", categoryView3.getCategory3Name());
					return jsonObject3;
				}).collect(Collectors.toList()));
			});

		});

		return jsonObjects;
	}

	@Override
	public List<BaseAttribute> findAttribute(Long category1Id) {
		return baseAttributeMapper.findAttribute(category1Id);
	}
}
